package com.njcb.ams.store.text.transform;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class UtilsCommon {
	private static final Logger logger = LoggerFactory.getLogger(UtilsCommon.class);
	/**
	 * 指示有效的数据条目
	 */
	public static int CHECK_RETURN_CODE_SUCCESS = 1;

	/**
	 * 指示无效的数据条目,但继续处理下一条数据
	 */
	public static int CHECK_RETURN_CODE_FAIL = 2;

	/**
	 * 指示无效的数据条目,不继续处理下一条数据 {@link #CHECK_RETURN_CODE_FAIL}
	 */
	public static int CHECK_RETURN_CODE_ERROR = 3;

	public static boolean isEmpty(String str) {
		return ((str == null) || (str.length() == 0));
	}

	public static void writeStringToFile(File file, String data, String encoding) throws IOException {
		OutputStream out = null;
		try {
			out = openOutputStream(file);
			write(data, out, encoding);
		} finally {
			closeQuietly(out);
		}
	}

	public static void closeQuietly(OutputStream output) {
		try {
			if (output != null) {
				output.close();
			}
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		}
	}

	public static void write(String data, OutputStream output, String encoding) throws IOException {
		if (data != null) {
			if (encoding == null) {
				write(data, output);
			} else {
				output.write(data.getBytes(encoding));
			}
		}
	}

	public static void write(String data, OutputStream output) throws IOException {
		if (data != null) {
			output.write(data.getBytes());
		}
	}

	public static FileOutputStream openOutputStream(File file) throws IOException {
		if (file.exists()) {
			if (file.isDirectory()) {
				throw new IOException("文件 '" + file + "' 是个文件夹");
			}
			if (file.canWrite()) {
				return new FileOutputStream(file);
			}
			throw new IOException("文件 '" + file + "' 不能写入");
		}

		File parent = file.getParentFile();
		if ((parent != null) && (!(parent.exists())) && (!(parent.mkdirs()))) {
			throw new IOException("文件 '" + file + "' 不存在");
		}
		return new FileOutputStream(file);
	}
}
